package com.arges.web.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 系统初始化时加载系统配置文件
 * 
 * @author arges
 * 
 */
public class PropertiesUtils
{

	private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtils.class);

	public static final String IS_MUL_SERVER_USE_SAME_DB = "multipleServiceConnectToSameDB";

	/*
	 * 存放读取到的系统路径下的配置文件信息
	 */
	private static Map<String, String> configMap = null;

	/**
	 * 初始化加载系统配置文件
	 * 
	 * @param filePath 文件路径
	 */
	public static void init(String filePath)
	{
		configMap = PropertiesUtils.loadConfigureProperties(filePath + Constant.CONFIGUR_PROPERTIES);
	}

	/**
	 * 将配置文件properties数据读取到map集合中
	 * 
	 * @param filePath 文件路径
	 * @return
	 */
	public static Map<String, String> loadConfigureProperties(String filePath)
	{
		Map<String, String> map = new HashMap<String, String>();
		FileInputStream fin = null;
		InputStreamReader isr = null;
		try
		{
			File file = new File(filePath);
			if (null != file)
			{
				fin = new FileInputStream(file);
				isr = new InputStreamReader(fin, "UTF-8");
				Properties properties = new Properties();
				properties.load(isr);
				if (null != properties)
				{
					Iterator<Entry<Object, Object>> iterator = properties.entrySet().iterator();
					while (iterator.hasNext())
					{
						Entry<Object, Object> entry = iterator.next();
						map.put(entry.getKey().toString(), entry.getValue().toString());
					}
				}
			}
		}
		catch (Exception e)
		{
			LOGGER.error("load file error, fileName is " + filePath, e);
		}
		finally
		{
			try
			{
				if (null != isr)
				{
					isr.close();
				}
				if (null != fin)
				{
					fin.close();
				}
			}
			catch (IOException e)
			{
				LOGGER.error("IO close error", e);
			}
		}
		return map;
	}

	public static String getConfigurValueByKey(String key)
	{
		return configMap.get(key);
	}

	/**
	 * 根据键值获取对应的整型数据value
	 * 
	 * @param configKey
	 * @return
	 */
	public static Integer getInt(String configKey)
	{
		Integer result = null;
		try
		{
			if (null != getConfigurValueByKey(configKey))
			{
				result = Integer.parseInt(getConfigurValueByKey(configKey));
			}
		}
		catch (NumberFormatException e)
		{
			LOGGER.error("NumberFormat error.key is " + configKey, e);
		}
		return result;
	}

	/**
	 * 判断是否包含某个key值
	 * 
	 * @param configKey
	 * @return
	 */
	public static boolean containsKey(String configKey)
	{
		return configMap.containsKey(configKey);
	}

	public static boolean isConfigOn(String configKey)
	{
		return containsKey(configKey) && "true".equalsIgnoreCase(getConfigurValueByKey(configKey));
	}
}
